package com.hefan.api.service.live;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.cat.common.entity.Page;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.bean.Message;
import com.hefan.common.ons.service.ONSProducer;
import com.hefan.common.util.DynamicProperties;
import com.hefan.common.util.MapUtils;
import com.hefan.live.bean.LiveRoomPersonVo;
import com.hefan.live.bean.RobotListenerVo;
import com.hefan.live.itf.LiveImOptService;
import com.hefan.live.itf.LivingRedisOptService;
import com.hefan.live.itf.RoomEnterExitOptService;
import java.util.List;
import java.util.Map;
import com.hefan.notify.itf.ItemsStaticService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 进入直播间处理
 * 
 * Created by kevin_zhang on 11/17/16.
 */
@Component
public class LivingLocalService {
	public Logger logger = LoggerFactory.getLogger(LivingLocalService.class);

	@Reference
	RoomEnterExitOptService roomEnterExitOptService;
	// @Reference
	// PoolOptService poolOptService;
	@Reference
	LiveImOptService liveImOptService;
	@Reference
	ItemsStaticService itemsStaticService;
	@Reference
	ONSProducer onsProducer;
	@Reference
	LivingRedisOptService livingRedisOptService;

	/**
	 * 检查用户能否进入直播间
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ResultBean enterLiveRoomCheck(String userId, int chatRoomId, String liveUuid, String authId,
			String deviceToken) {
		ResultBean resultBean = new ResultBean(ResultCode.SUCCESS);
		List livePersonsList = roomEnterExitOptService.enterLiveRoomCheck(userId);

		if (null != livePersonsList && livePersonsList.size() > 0) {
			for (int i = 0; i < livePersonsList.size(); i++) {
				Map map = (Map) livePersonsList.get(i);
				String _userId = MapUtils.getStrValue(map, "userId", "");// 进入直播间用户id
				String _deviceToken = MapUtils.getStrValue(map, "deviceToken", "");// 设备deviceToken
				String _authId = MapUtils.getStrValue(map, "authId", "");// 主播id
				int _chatRoomId = MapUtils.getIntValue(map, "chatRoomId", -1);// 进入直播间对应聊天室id
				String _liveUuid = MapUtils.getStrValue(map, "liveUuid", "");// 直播间UUID
				if (StringUtils.isNotBlank(_userId) && _chatRoomId > 0 && StringUtils.isNotBlank(_liveUuid)) {
					if (liveUuid.equals(_liveUuid) && StringUtils.isNotBlank(deviceToken)
							&& deviceToken.equals(_deviceToken)) {
						logger.info("用户同一个设备，进入同一个直播间");
						return resultBean;
					} else {
						// 发送 207 IM消息到对应直播间，让该用户退出直播间
						liveImOptService.liveStartClear(_userId, _liveUuid, _chatRoomId);
					}
				}
				// 用户离开上一个直播间队列消息发送
				roomEnterExitOptService.sendExitRoomMsgQueue(_authId, _chatRoomId, _liveUuid, _userId);
			}
		}
		if (null != livePersonsList && livePersonsList.size() > 0) {
			resultBean.setCode(ResultCode.LiveRoomRepeat.get_code());
			resultBean.setMsg(ResultCode.LiveRoomRepeat.getMsg());
			resultBean.setData(livePersonsList);
		}
		return resultBean;
	}

	/**
	 * 用户进入直播间
	 */
	@SuppressWarnings({ "rawtypes" })
	public ResultBean enterLiveRoomOperate(LiveRoomPersonVo user, String liveUuid, int chatRoomId, String authId,
										   String token) {
		ResultBean resultBean = roomEnterExitOptService.enterRoom(user, liveUuid, chatRoomId, authId, token);

		// 用户进入直播间队列消息发送
		roomEnterExitOptService.sendEnterRoomMsgQueue(authId, chatRoomId, liveUuid, user.getUserId(),
				user.getUserType(), user.getUserLevel(), user.getNickName(), user.getHeadImg());
		return resultBean;
	}

	/**
	 * 用户离开直播间
	 */
	public ResultBean exitLiveRoomOperate(String userId, int chatRoomId, String liveUuid, String authId) {
		ResultBean resultBean = roomEnterExitOptService.exitRoom(userId, chatRoomId, liveUuid, authId);

		// 用户离开直播间队列消息发送
		roomEnterExitOptService.sendExitRoomMsgQueue(authId, chatRoomId, liveUuid, userId);
		return resultBean;
	}

	/**
	 * 获取直播间用户列表
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Page getOnlineUserlist(String authId, Page page) {
		page.setTotalItems(roomEnterExitOptService.getLiveRoomPeoleCount(authId));
		page.setTotalPages(page.getTotalPages());
		page.setResult(roomEnterExitOptService.getOnlineUserlist(authId, page.pageNo, page.pageSize));
		return page;
	}

	/**
	 * 真人带机器人进入直播间
	 */
	@SuppressWarnings("rawtypes")
	@Async
	public void addRobotWhenJoin(String liveUuid, int chatRoomId, String anchorId) {
		try {
			livingRedisOptService.addLastJoinTime(liveUuid);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("更新直播间最后进入时间失败");
		}
		Message message = new Message();
		RobotListenerVo robotListenerVo = new RobotListenerVo();
		robotListenerVo.setAnchId(anchorId);
		robotListenerVo.setLiveUuid(liveUuid);
		robotListenerVo.setChatRoomId(chatRoomId);
		robotListenerVo.setInOrOut(1);
		message.put("vo", JSON.toJSONString(robotListenerVo));
		message.setTopic(TopicRegistry.HEFAN_ROBOT_WHEN_LIVING);
		String onsEnv = DynamicProperties.getString("ons.env");
		message.setTag(onsEnv);
		onsProducer.sendMsg(message);
	}

	/**
	 * 真人带机器人离开直播
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Async
	public void removeRobotWhenLeft(int chatRoomId, String liveUuid, String anchorId) {
		Message message = new Message();
		RobotListenerVo robotListenerVo = new RobotListenerVo();
		robotListenerVo.setAnchId(anchorId);
		robotListenerVo.setLiveUuid(liveUuid);
		robotListenerVo.setChatRoomId(chatRoomId);
		robotListenerVo.setInOrOut(0);
		message.put("vo", JSON.toJSONString(robotListenerVo));
		message.setTopic(TopicRegistry.HEFAN_ROBOT_WHEN_LIVING);
		String onsEnv = DynamicProperties.getString("ons.env");
		message.setTag(onsEnv);
		onsProducer.sendMsg(message);
	}

	/**
	 * 更新最新、热门列表页静态文件
	 */
	@Async
	public void liveStartOpt() {
		itemsStaticService.getLivingList();
	}

	/**
	 * 开播清除用户及机器人信息
	 */
	public void endLiveClearNoAsync(String authorId) {
		roomEnterExitOptService.endLiveClear(authorId);
	}

	/**
	 * 获取直播间实际观看人数
	 */
	public Long getLiveRoomPeoleCount(String authId) {

		return roomEnterExitOptService.getLiveRoomPeoleCount(authId);
	}


	// /**
	// * 进入直播间排队处理
	// */
	// @SuppressWarnings("rawtypes")
	// public ResultBean enterQueue(LivingVo item) {
	// return poolOptService.enterQueueOperate(item);
	// }

	/**
	* 踢出的是机器人的情况
	* @param anchId
	*/
	@Async
	public void outRobot(String anchId,String robotId) {
		livingRedisOptService.outRobot(anchId,robotId);
	}
}
